/*
 * Copyright 2014 Semidata. All rights reserved.
 */
package com.semidata.trp.report.merge;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author shewei@semidata.com, She Wei
 *
 */
public class MergeOutput {
	private static int BUFFER_SIZE = 4 * 1024 * 1024;

	private FileOutputStream out;
	private byte[] buffer = new byte[BUFFER_SIZE];
	private int offset;

	public MergeOutput(File destDir, char suffix) {
		if (!destDir.exists())
			destDir.mkdirs();
		this.offset = 0;
		try {
			this.out = new FileOutputStream(new File(destDir, "data_" + suffix));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public void close() {
		try {
			out.write(buffer, 0, offset);
			offset = 0;
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void write(String str) {
		if (str == null || str.length() == 0) {
			System.out.println("empty string");
		}
		
		byte[] bytes = str.getBytes();

		if (offset + bytes.length + 1 <= BUFFER_SIZE) {
			System.arraycopy(bytes, 0, buffer, offset, bytes.length);
			offset += bytes.length;
			buffer[offset] = '\n';
			offset++;
		} else if (bytes.length + 1 > BUFFER_SIZE) {
			try {
				out.write(buffer, 0, offset);
				out.write(bytes);
				out.write("\n".getBytes());
				offset = 0;
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			try {
				out.write(buffer, 0, offset);
				offset = 0;
				System.arraycopy(bytes, 0, buffer, offset, bytes.length);
				buffer[offset] = '\n';
				offset++;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

}
